//
//  Date+Extension.swift
//  Swift-Tools
//
//  Created by 深圳-周星驰 on 2020/10/15.
//

import Foundation

extension Date {
    
    /// 根据给定的时间戳和时间格式，转换成日期格式字符串
    static func string(with timeStamp: String, dateFormat: String) -> String {
        let interval: TimeInterval = TimeInterval.init(timeStamp)!
        let date = Date(timeIntervalSince1970: interval)
        let dateformatter = DateFormatter()
        dateformatter.dateFormat = dateFormat
        return dateformatter.string(from: date)
    }
    
    /// 根据给定的timeInterval和时间格式，转换成日期格式字符串
    static func string(with timeInterval: Double, dateFormat: String) -> String {
        let date = Date(timeIntervalSince1970: timeInterval)
        let dateformatter = DateFormatter()
        dateformatter.dateFormat = dateFormat
        return dateformatter.string(from: date)
    }
    
    /// 把ISO格式的时间字符串，转换成Date
    static func date(withISOFormatString dateString: String?) -> Date? {
        return ISOFormatString?.date(from: dateString ?? "")
    }
    
    static let ISOFormatString: DateFormatter? = {
        var formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
        return formatter
    }()
    
    /// 把时间字符串根据其相应的格式，转换成Date
    static func date(with dateString: String?, dateFormat: String?) -> Date? {
        let formatter = DateFormatter()
        formatter.dateFormat = dateFormat
        return formatter.date(from: dateString ?? "")
    }
    
    /// 把Date转换成设定的日期格式字符串，如 yyyy-MM-dd HH:mm:ss
    func string(withFormat dateFormat: String?) -> String? {
        let formatter = DateFormatter()
        formatter.dateFormat = dateFormat
        formatter.locale = NSLocale.current
        return formatter.string(from: self)
    }

    /// 时间年月日等转时间戳
    /// - Parameters:
    ///   - time: 需要转的时间
    ///   - timeType: 时间类型
    static func timeStringToInterval(time : String, dateFormat: String) -> TimeInterval {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = dateFormat
        
        let date = dateFormatter.date(from: time)
        let timeStamp = date?.timeIntervalSince1970
        
        return timeStamp!
    }
    
    ///当前时间是哪一年
    var year:Int {
        let calendar =  Calendar.current
        var set:Set<Calendar.Component> = []
        set.insert(Calendar.Component.year)
        set.insert(Calendar.Component.weekday)
        set.insert(Calendar.Component.month)
        set.insert(Calendar.Component.day)
        let comp = calendar.dateComponents(set, from: self)
        return comp.year ?? 2020
    }
    
    //日期 -> 字符串
    func dateToString(dateFormat:String = "yyyy-MM-dd HH:mm:ss") -> String {
        let formatter = DateFormatter()
        formatter.locale = Locale.init(identifier: "zh_CN")
        formatter.dateFormat = dateFormat
        let date = formatter.string(from: self)
        return date
    }
}
